package com.tiance.domainservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.tiance.dal.dao.MemberAuthFileDAO;
import com.tiance.dal.dao.MemberAuthOpinionDAO;
import com.tiance.dal.dao.MemberAuthenticationInfoDAO;
import com.tiance.dal.dao.MemberDAO;
import com.tiance.dal.dataobject.*;
import com.tiance.domainservice.domain.IntegrationDomain;
import com.tiance.domainservice.domain.MemberAuthOpinionDomain;
import com.tiance.domainservice.domain.MemberAuthenticationInfoDomain;
import com.tiance.domainservice.service.IntegrationService;
import com.tiance.domainservice.service.MemberAuthService;
import com.tiance.enums.*;
import com.tiance.exception.BusinessException;
import com.tiance.integration.idcard.IDCardUtil;
import com.tiance.page.QueryPage;
import com.tiance.utils.BeanConverterUtil;
import com.tiance.utils.MapUtil;
import com.tiance.utils.StringUtil;
import com.tiance.utils.Validator;
import com.tiance.vo.ImageVO;
import com.tiance.vo.MemberAuthenticationInfoVO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/2/18
 *
 * Description：
 *
 * Modification History:
 *
 */
@Service
public class MemberAuthServiceImpl implements MemberAuthService {

    /** logger */
    protected static final Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);

    @Resource
    private MemberDAO memberDAO;

    @Resource
    private MemberAuthenticationInfoDAO memberAuthenticationInfoDAO;
    @Resource
    private MemberAuthFileDAO           memberAuthFileDAO;
    @Resource
    private MemberAuthOpinionDAO        memberAuthOpinionDAO;


    @Autowired
    private IntegrationService integrationService;


    @Override
    public List<MemberAuthenticationInfoDO> queryMemberAuthApplyList(
            MemberAuthenticationInfoDomain domain) {

        Map<String,Object> paramMap= MapUtil.params2Map(new Object[]{ "memberId", StringUtil.trimNull(domain.getMemberId())},
                new Object[]{ "statusScope", domain.getStatusScope()},
                new Object[]{ "openid", StringUtil.trimNull(domain.getOpenid())});
        logger.info("开始查询会员审认证申请总数，参数:{}", JSON.toJSONString(paramMap));
        int count  =memberAuthenticationInfoDAO.queryMemberAuthApplyCount(paramMap);
        logger.info("开始查询会员审认证申请总数，返回总数:{}", count);


        if(0==count){
            return new ArrayList();
        }

        QueryPage queryPage = domain.getQueryPage();
        queryPage.setTotalItem(count);
        paramMap.put("queryPage", queryPage);
        if (queryPage.getEndRow() == 0) {
            queryPage.setStartRow(queryPage.getPageFristItem());
            queryPage.setEndRow(queryPage.getPageLastItem());
        }

        domain.setQueryPage(queryPage);
        logger.info("开始查询会员审认证申请列表数据，参数:{}", JSON.toJSONString(paramMap));
        List<MemberAuthenticationInfoDO> memberAuthApplyList =memberAuthenticationInfoDAO.queryMemberAuthApplyList(paramMap);
        logger.info("结束查询会员审认证申请列表数据，查询结果:{}", JSON.toJSONString(memberAuthApplyList));
        return memberAuthApplyList;
    }

    @Override
    public MemberAuthenticationInfoVO queryMemberAuthApplyDetail(
            MemberAuthenticationInfoDomain memberDomain)throws Exception {
        Map<String,Object> map= MapUtil.params2Map(new Object[]{ "memberId", memberDomain.getMemberId()},
                new Object[]{ "id", memberDomain.getId()},
                new Object[]{ "openid", memberDomain.getOpenid()});

        logger.info("开始查询会员认证数据，参数:{}", JSON.toJSONString(map));
        MemberAuthenticationInfoDO memberAuthenticationInfoDO=memberAuthenticationInfoDAO.queryMemberAuthApplyDetail(map);
        logger.info("结束查询会员认证数据，返回数据:{}", JSON.toJSONString(memberAuthenticationInfoDO));

        Validator.assertNull(memberAuthenticationInfoDO,"会员认证记录不存在!");
        Validator.assertNull(memberAuthenticationInfoDO.getId(),"会员认证记录不存在!");

        MemberAuthenticationInfoVO memberAuthenticationInfoVO=new MemberAuthenticationInfoVO();

        BeanConverterUtil.copyProperties(memberAuthenticationInfoVO,memberAuthenticationInfoDO);
        map.put("authenticationInfoId",memberAuthenticationInfoDO.getId());
        logger.info("开始查询会员认证材料数据，参数:{}", JSON.toJSONString(map));
        List<MemberAuthFileDO> memberAuthFileList=memberAuthFileDAO.queryMemberAuthFileList(map);
        logger.info("结束查询会员认证材料数据，返回数据:{}", JSON.toJSONString(memberAuthFileList));

         List<ImageVO> jobQualificationCertificateList= new ArrayList<>();
        if(CollectionUtils.isNotEmpty(memberAuthFileList)){
            for(MemberAuthFileDO memberAuthFileDO:memberAuthFileList){
                if(AuthFileTypeEnum.CHOOSE_JOB_CERTIFICATE.getCode().equals(memberAuthFileDO.getFileType())){
                    memberAuthenticationInfoVO.setChooseJobCertificateUrl(memberAuthFileDO.getFilePath());
                }
                if(AuthFileTypeEnum.ID_CARD_BACK.getCode().equals(memberAuthFileDO.getFileType())){
                    memberAuthenticationInfoVO.setIdCardBackUrl(memberAuthFileDO.getFilePath());
                }
                if(AuthFileTypeEnum.ID_CARD_FRONT.getCode().equals(memberAuthFileDO.getFileType())){
                    memberAuthenticationInfoVO.setIdCardFrontUrl(memberAuthFileDO.getFilePath());
                }
                if(AuthFileTypeEnum.JOB_QUALIFICATION_CERTIFICATE.getCode().equals(memberAuthFileDO.getFileType())){
                    ImageVO imageVO=new ImageVO();
                    imageVO.setName(memberAuthFileDO.getFileName());
                    imageVO.setUrl(memberAuthFileDO.getFilePath());
                    jobQualificationCertificateList.add(imageVO);
                }
                if(AuthFileTypeEnum.RETIREMENT_RESUME_CERTIFICATE.getCode().equals(memberAuthFileDO.getFileType())){
                    memberAuthenticationInfoVO.setRetirementResumeCertificateUrl(memberAuthFileDO.getFilePath());
                }
            }
        }
        memberAuthenticationInfoVO.setJobQualificationCertificateList(jobQualificationCertificateList);
        return memberAuthenticationInfoVO;
    }

    @Override
    public void auditMemberAuth(MemberAuthOpinionDomain memberDomain) {

        Map<String,Object> map= MapUtil.params2Map(new Object[]{ "id", memberDomain.getId()});
        logger.info("开始查询会员认证数据，参数:{}", JSON.toJSONString(map));
        MemberAuthenticationInfoDO memberAuthenticationInfoDO=memberAuthenticationInfoDAO.queryMemberAuthApplyDetail(map);
        logger.info("结束查询会员认证数据，返回数据:{}", JSON.toJSONString(memberAuthenticationInfoDO));
        Validator.assertNull(memberAuthenticationInfoDO,"会员认证信息不存在!");
        Validator.assertNull(memberAuthenticationInfoDO.getId(),"会员认证信息不存在!");


        map.remove("id");
        map.put("memberId",memberAuthenticationInfoDO.getMemberId());
        logger.info("开始查询会员数据，参数:{}", JSON.toJSONString(map));
        MemberDO oldMemberDO=memberDAO.queryMember(map);
        logger.info("结束查询会员数据，返回数据:{}", JSON.toJSONString(oldMemberDO));
        Validator.assertNull(oldMemberDO,"会员不存在!");
        Validator.assertNull(oldMemberDO.getId(),"会员不存在!");
        Validator.assertTrue(MemberStatusEnum.VERIFY_SUCCESS.getCode().equals(oldMemberDO.getMemberStatus()),"会员已经认证成功,请勿重复认证!");
        memberDomain.setMemberId(oldMemberDO.getId());



        MemberAuthOpinionDO memberAuthOpinionDO=new MemberAuthOpinionDO();
        memberAuthOpinionDO.setMemberId(memberDomain.getMemberId());
        //memberAuthOpinionDO.setAuthUserId(1L); todo
       // memberAuthOpinionDO.setAuthUserName("admin");
        memberAuthOpinionDO.setOpenid(memberDomain.getOpenid());
        memberAuthOpinionDO.setAuthenticationInfoId(memberAuthenticationInfoDO.getId());

        MemberDO updateMemberDO=new MemberDO();
        updateMemberDO.setId(memberDomain.getMemberId());
        //必须三个都认证成功 才算认证成功
        if(MemberAuthStatusEnum.VERIFY_SUCCESS.getCode().equals(memberDomain.getAuthState1())&&
           MemberAuthStatusEnum.VERIFY_SUCCESS.getCode().equals(memberDomain.getAuthState2())&&
           MemberAuthStatusEnum.VERIFY_SUCCESS.getCode().equals(memberDomain.getAuthState3())){
            updateMemberDO.setMemberStatus(MemberStatusEnum.VERIFY_SUCCESS.getCode());
            updateMemberDO.setMemberType(MemberTypeEnum.VERIFIED_MEMBER.getCode());
            memberAuthOpinionDO.setAuthState(MemberAuthStatusEnum.VERIFY_SUCCESS.getCode());
        }else{
            updateMemberDO.setMemberStatus(MemberStatusEnum.BACKGROUND_VERIFY_FAIL.getCode());
            memberAuthOpinionDO.setAuthState(MemberAuthStatusEnum.VERIFY_FAIL.getCode());
        }

        memberAuthOpinionDO.setAuthOpinion1(memberDomain.getAuthOpinion1());
        memberAuthOpinionDO.setAuthOpinion2(memberDomain.getAuthOpinion2());
        memberAuthOpinionDO.setAuthOpinion3(memberDomain.getAuthOpinion3());

        logger.info("开始更新会员数据，参数:{}", JSON.toJSONString(updateMemberDO));
        Long count=memberDAO.updateMember(updateMemberDO);
        logger.info("结束更新会员数据，是否更新成功:{}", count>0?true:false);
        if(count<1){
            throw new BusinessException("更新会员信息失败");
        }

        logger.info("开始插入会员认证数据，参数:{}", JSON.toJSONString(memberAuthOpinionDO));
        Long memberAuthOpinionCount=memberAuthOpinionDAO.insert(memberAuthOpinionDO);
        logger.info("结束插入会员数据，是否插入成功:{}", memberAuthOpinionCount>0?true:false);
        if(memberAuthOpinionCount<1){
            throw new BusinessException("更新会员认证信息失败");
        }

        if(MemberStatusEnum.VERIFY_SUCCESS.getCode().equals(updateMemberDO.getMemberStatus())){
            IntegrationDomain integrationDomain=new IntegrationDomain();
            integrationDomain.setIntegrationType(IntegrationTypeEnum.INTEGRATION.getCode());
            integrationDomain.setMemberId(updateMemberDO.getId());
            integrationDomain.setBelongType(IntegrationBelongTypeEnum.MEMBER.getCode());
            integrationDomain.setIntegrationRuleCode(IntegrationRuleCodeEnum.MEMBER_VERIFY_SUCCESS);
            integrationService.addIntegration(true,integrationDomain);


        }
    }

    @Override
    public void updateAuthInfo(MemberAuthenticationInfoDomain memberDomain) {
        MemberAuthenticationInfoDO memberAuthenticationInfoDO =new MemberAuthenticationInfoDO();
        memberAuthenticationInfoDO.setMemberId(memberDomain.getMemberId());
        memberAuthenticationInfoDO.setRealName(memberDomain.getRealName());

        logger.info("开始更新会员审认证申请信息数据，参数:{}", JSON.toJSONString(memberAuthenticationInfoDO));
        Long updateAuthCount=memberAuthenticationInfoDAO.update(memberAuthenticationInfoDO);
        logger.info("结束更新会员审认证申请信息数据，更新个数:{}", updateAuthCount);
        if(updateAuthCount<1){
            throw new BusinessException("更新会员认证申请信息失败");
        }
        MemberDO updateMemberDO=new MemberDO();
        updateMemberDO.setId(memberDomain.getMemberId());
        updateMemberDO.setMemberSex(memberDomain.getMemberSex());
        updateMemberDO.setPhone(memberDomain.getPhone());
        updateMemberDO.setMemberEmail(memberDomain.getMemberEmail());

        logger.info("开始更新会员数据，参数:{}", JSON.toJSONString(updateMemberDO));
        Long updateMemberCount=memberDAO.updateMember(updateMemberDO);
        logger.info("结束更新会员数据，是否更新成功:{}", updateMemberCount>0?true:false);
        if(updateMemberCount<1){
            throw new BusinessException("更新会员失败");
        }


    }
}
